<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="480"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        :footer="null"
        class="bindingModal"
        @cancel="handleCancle"
    >
        <div class="binding-body">
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol" :model="formState" :rules="rules" ref="formRef">
                <a-row>
                    <a-col :span="20">
                        <a-form-item :label="t('yl.bindingDevCode')" name="deviceCode">
                            <a-input
                                v-model:value="formState.deviceCode"
                                :placeholder="t('yl.bindingDevCode')"
                                :disabled="tmpList.length"
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :span="4">
                        <a-form-item>
                            <a-button type="primary" @click.prevent="handTemplate(tmpList.length ? 'edit' : 'onSubmit')">{{
                                tmpList.length ? '编辑' : '确认'
                            }}</a-button>
                        </a-form-item></a-col
                    >
                </a-row>
                <a-row v-for="(item, index) in formState.templateItems" :key="index">
                    <a-col :span="20" v-if="tmpList.length">
                        <a-form-item
                            :label="t('yl.bindingTmp')"
                            :name="['templateItems', index, 'templateCode']"
                            :rules="{
                                required: true,
                                message: t('yl.tmpModelFormTips'),

                                trigger: 'change',
                            }"
                        >
                            <a-select v-model:value="item.templateCode" style="width: 100%" @change="changTemplateCode">
                                <a-select-option :value="item.templateCode" v-for="(item, index) in tmpList" :key="index">{{
                                    item.templateName
                                }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="20" v-if="item.items.length">
                        <a-form-item
                            :label="t('yl.bindingMerchanName')"
                            v-for="(items1, index1) in item.items"
                            :key="index1"
                            :name="['templateItems', index, 'items', index1, 'goodsId']"
                            :rules="{
                                required: true,
                                message: t('yl.tmpModelFormTips'),
                                type: 'number',
                                trigger: 'change',
                            }"
                        >
                            <a-select
                                v-model:value="items1.goodsId"
                                style="width: 100%"
                                @change="changGoodsId(item.items, items1, index1)"
                            >
                                <a-select-option
                                    :value="good.id"
                                    v-for="(good, goodIndex) in goodsSkuList"
                                    :key="goodIndex"
                                    :disabled="getDisable(good.id)"
                                    >{{ good.name }}</a-select-option
                                >
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row v-if="tmpList.length">
                    <a-col :span="20">
                        <a-form-item :label="t('yl.bindingJqArea')" name="precinct">
                            <a-select v-model:value="formState.precinct" style="width: 100%">
                                <a-select-option :value="item.value" v-for="(item, index) in precinctList" :key="index">{{
                                    item.label
                                }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <div class="ant-modal-footer">
            <a-button @click="handleCancel">取消</a-button>
            <a-button @click="onSubmit">确定</a-button>
        </div>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, watch, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import _ from 'lodash';
import ylTreeselectVue from '@/components/ylTreeselect.vue';
import { getAppsTemplate, postAppsActivation } from '@/api/device/deviceApps';
import { getskuGoodsSku } from '@/api/goods';
import { PaginationQuery, Pagination } from '@/types/table';
interface DeptState {
    deviceCode: string;
    specsCode: string | number;
    id: string | number;
    nfcCode: string | number;
}

// 表单校验规则
const initRules = (t: fn) => {
    return {
        deviceCode: [{ required: true, message: t('yl.inputNameStand'), trigger: 'blur' }],
        precinct: [{ required: true, message: t('yl.bindingJqArea'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'roleModel',
    components: {
        ylTreeselectVue,
    },
    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },
        title: {
            type: String,
        },
        selectEditModel: {
            type: Array,
            default: () => [],
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        dept: {
            type: Object,
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        const { t } = useI18n();
        // const a = reactive({
        //     showModal: computed(() => props.visible),
        //     models: computed(() => props.selectModels as NormalObj[]),
        // })
        const showModal = computed(() => props.visible);
        let models = computed(() => props.selectEditModel as NormalObj[]);
        const formState = reactive({
            deviceCode: '',
            precinct: '',
            templateItems: [
                {
                    items: [],
                    templateCode: '',
                },
            ],
        });
        const tableQuery: PaginationQuery = reactive({
            page: 0,
            size: 10,
            sort: 'id,desc',
            blurry: '',
        });
        const tmpList: any = ref([]);
        const goodsSkuList: any = ref([]);
        const selectedOptions = ref([]);
        const precinctList = ref([
            {
                value: '1',
                label: '1区',
            },
        ]);
        // 编辑时赋值
        watch(
            () => props.dept,
            (dept) => {
                const { deviceCode, specsCode, id, nfcCode } = dept as DeptState;
                formState.deviceCode = deviceCode;
                formState.specsCode = specsCode;
                formState.id = id;
                formState.nfcCode = nfcCode;
            }
        );

        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        onMounted(async () => {
            getskuGoodsSkuList();
        });
        // 取消
        const handleCancle = () => {
            return emit('cancle');
        };
        const handTemplate = async (type: string) => {
            console.log(type);
            if (type == 'edit') {
                formState.deviceCode = '';
                tmpList.value = [];
                formState.templateItems.items = [];
            } else {
                const { content } = await getAppsTemplate({ deviceCode: formState.deviceCode });
                tmpList.value = content;
            }
        };
        const changTemplateCode = (val: string) => {
            formState.templateItems[0].items = [];
            let items = [];
            for (let i = 0; i < tmpList.value.length; i++) {
                if (tmpList.value[i].templateCode == val) {
                    console.log(tmpList.value[i]);
                    let list = tmpList.value[i].templateCommon;
                    for (let j = 0; j < list.length; j++) {
                        items.push({
                            goodsId: null,
                            imageUrl: '',
                            templateCommonId: list[j].templateCommonId,
                        });
                    }

                    break;
                }
            }
            formState.templateItems[0].items = items;
        };
        // 获取表格数据
        const getskuGoodsSkuList = async () => {
            const { content, totalElements } = await getskuGoodsSku(tableQuery);
            goodsSkuList.value = content;
        };
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                console.log(formState);
                postAppsActivation(formState).then((res) => {
                    return emit('submit');
                });
            });
        };
        const getDisable = (val) => {
            // console.log(val);
            if (selectedOptions.value.indexOf(val) >= 0) {
                return true;
            } else {
                return false;
            }
        };
        const changGoodsId = (list: array, item: any, index: number) => {
            // console.log(item, index);
            selectedOptions.value[index] = item.goodsId;
            for (let i = 0; i < goodsSkuList.value.length; i++) {
                if (goodsSkuList.value[i].id == item.goodsId) {
                    console.log(goodsSkuList.value[i].id, item.goodsId);
                    console.log(list[index].imageUrl);
                    list[index].imageUrl = 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png';
                }
            }
        };
        const handleCancel = () => {
            return emit('cancle');
        };
        return {
            formRef,
            labelCol: { span: 5 },
            wrapperCol: { span: 17 },
            showModal,
            models,
            formState,
            t,
            rules,
            handTemplate,
            handleCancle,
            tmpList,
            changTemplateCode,
            onSubmit,
            getskuGoodsSkuList,
            tableQuery,
            goodsSkuList,
            getDisable,
            selectedOptions,
            changGoodsId,
            precinctList,
            handleCancel,
        };
    },
});
</script>
<style lang="scss">
.bindingModal .ant-modal-body {
    padding: 0;
}
.binding-body {
    padding: 24px;
}
</style>
